package dbopr

import (
	"myCloud/dbmodel"
)

type UserDeviceProvider struct{}

func NewUserDeviceProvider() *UserDeviceProvider {
	return &UserDeviceProvider{}
}

func (*UserDeviceProvider) ListDevices(userId int) ([]dbmodel.UserDevice, error) {
	var devs []dbmodel.UserDevice
	err := dbSession.Where("user_id=?", userId).Find(&devs).Error
	return devs, err
}

func (*UserDeviceProvider) FindOrCreate(userID int, brand, model, hash string) (*dbmodel.UserDevice, error) {
	var out dbmodel.UserDevice
	err := dbSession.Where(dbmodel.UserDevice{
		UserID: userID,
		Hash:   hash,
	}).Attrs(dbmodel.UserDevice{
		Name:     brand,
		Brand:    brand,
		DevModel: model,
	}).FirstOrCreate(&out).Error
	return &out, err
}

func (*UserDeviceProvider) GetById(id int) (*dbmodel.UserDevice, bool, error) {
	var out dbmodel.UserDevice
	query := dbSession.Where("id=?", id).First(&out)
	if query.RecordNotFound() {
		return nil, true, nil
	}
	return &out, false, query.Error
}
